package com.yugao.fintech.antelope.system.controller;

import com.yugao.fintech.antelope.base.security.utils.SecurityUtils;
import com.yugao.fintech.antelope.base.log.OperateLog;
import com.yugao.fintech.antelope.base.log.enums.BusinessType;
import com.yugao.fintech.antelope.base.model.module.auth.LoginUser;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.antelope.base.ram.RamPersonalResource;
import com.yugao.fintech.antelope.system.model.entity.SysRole;
import com.yugao.fintech.antelope.system.model.rqrs.dept.DeptResp;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.SwitchTenantReq;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.SwitchTenantResp;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.TenantResp;
import com.yugao.fintech.antelope.system.model.rqrs.user.LoginUserDeptGetResp;
import com.yugao.fintech.antelope.system.model.rqrs.user.UserInfoResp;
import com.yugao.fintech.antelope.system.model.rqrs.user.UserProfileUpdateReq;
import com.yugao.fintech.antelope.system.model.rqrs.user.UserResp;
import com.yugao.fintech.antelope.system.service.*;
import com.yugao.fintech.framework.core.response.Resp;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 个人信息 业务处理
 */
@Slf4j
@RestController
@RequestMapping("/user/profile")
@RamPersonalResource(action = "sys:user:profile", url = "/user/profile", name = "个人信息")
public class SysUserProfileController {

    @Autowired
    private SysTenantUserService tenantUserService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysTenantService tenantService;
    @Autowired
    private SysRoleService roleService;

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public Resp<UserInfoResp> getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(loginUser.getIsTenantOwner(), loginUser.getUserId());

        // 角色集合
        List<SysRole> roleList = roleService.listRoleByUserId(loginUser.getUserId());
        Set<String> roles = roleList.stream().map(SysRole::getRoleCode).collect(Collectors.toSet());
        UserResp userResp = userService.getUserById(loginUser.getUserId());

        UserInfoResp resp = new UserInfoResp();
        resp.setUserInfo(userResp);
        resp.setRoles(roles);
        resp.setTenant(tenantService.getEffectiveTenant(TenantContextHolder.get().getTenantId()));
        resp.setPermissions(permissions);
        return Resp.ok(resp);
    }

    /**
     * 修改用户
     */
    @OperateLog(summary = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateProfile")
    public Resp<?> updateProfile(@RequestBody @Validated UserProfileUpdateReq req) {
        return userService.updateUserProfile(req) ?
                Resp.ok() : Resp.fail("修改个人信息异常, 请联系管理员");
    }

    /**
     * 查询当前用户的所有部门/当前部门编码
     * @return 结果
     */
    @GetMapping(value = "/getUserDept")
    public Resp<LoginUserDeptGetResp> getCurrentUserDept() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<DeptResp> deptList = this.tenantUserService.listUserDept(loginUser.getUserId());
        LoginUserDeptGetResp resp = new LoginUserDeptGetResp();
        resp.setList(deptList);
        resp.setCurrentDeptId(loginUser.getCurrentDeptId());
        return Resp.ok(resp);
    }

    /**
     * 头像上传
     */
//    @OperateLog(summary = "用户头像", businessType = BusinessType.UPDATE)
//    @PostMapping("/avatar")
//    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
//        if (!file.isEmpty()) {
//            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//            R<SysFile> fileResult = remoteFileService.upload(file);
//            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
//                return AjaxResult.error("文件服务异常，请联系管理员");
//            }
//            String url = fileResult.getData().getUrl();
//            if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", url);
//                // 更新缓存用户头像
//                loginUser.getSysUser().setAvatar(url);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
//        }
//        return AjaxResult.error("上传图片异常，请联系管理员");
//    }


    /**
     * 返回的第一个为上一次登录的
     */
    @ApiOperation(value = "查询当前用户的所有有效租户")
    @GetMapping(value = "/listTenant")
    public Resp<List<TenantResp>> listUserTenant() {
        return Resp.ok(tenantUserService.listUserTenant());
    }

    @ApiOperation(value = "查询当前用户的所有有效租户")
    @GetMapping(value = "/listTenantTree")
    public Resp<List<TenantResp>> listUserTenantTree() {
        return Resp.ok(tenantUserService.listUserTenantTree());
    }

    @ApiOperation(value = "授权用户访问某个租户")
    @PostMapping(value = "/switchTenant")
    public Resp<SwitchTenantResp> switchTenant(@RequestBody SwitchTenantReq req) {
        SwitchTenantResp resp = tenantUserService.switchTenant(req);
        return Resp.ok(resp);
    }

    @ApiOperation(value = "app-初始化租户信息")
    @PostMapping(value = "/initTenant")
    public Resp<?> initTenant() {
        Long tenantId = TenantContextHolder.get().getTenantId();
        tenantUserService.initTenant(tenantId);
        return Resp.ok();
    }
}